package com.itheima.restkeeper.face;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.UserFace;
import com.itheima.restkeeper.enums.UserEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Role;
import com.itheima.restkeeper.pojo.User;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.UserVo;
import com.itheima.restkeeper.service.IUserAdapterService;
import com.itheima.restkeeper.service.IUserService;
import com.itheima.restkeeper.utils.BeanConv;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import com.itheima.restkeeper.utils.ResponseWrapBuild;
import com.sun.corba.se.spi.ior.iiop.IIOPFactories;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserFaceImpl.java
 * @Description 用户dubbo服务实现
 */
@Slf4j
@DubboService(version = "${dubbo.application.version}",timeout = 5000,
    methods ={
        @Method(name = "findUserVoPage",retries = 2),
        @Method(name = "createUser",retries = 0),
        @Method(name = "updateUser",retries = 0),
        @Method(name = "deleteUser",retries = 0)
    })
public class UserFaceImpl implements UserFace {

    @DubboReference(version = "${dubbo.application.version}",check = false)
    AffixFace affixFace;

    @Autowired
    IUserService userService;

    @Autowired
    IUserAdapterService userAdapterService;

    @Override
    public Page<UserVo> findUserVoPage(UserVo userVo,
                                       int pageNum,
                                       int pageSize)throws ProjectException {
        try {
            //执行查询
            Page<User> page = userService.findUserVoPage(userVo, pageNum, pageSize);
            Page<UserVo> userVoPage = new Page<>();
            BeanConv.toBean(page,userVoPage);
            //结果集转换
            List<User> userList = page.getRecords();
            List<UserVo> userVoList = BeanConv.toBeanList(userList, UserVo.class);

            if (!EmptyUtil.isNullOrEmpty(userList)){
                //遍历vo集合
                userVoList.forEach(userVO->{
                    //处理附件
                    List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(userVO.getId());
                    //判断集合是否为空
                    if (!EmptyUtil.isNullOrEmpty(affixVos)) {
                        userVO.setAffixVo(affixVos.get(0));
                    }
                    //处理角色 ,查询出角色列表
                    List<Role> roleList = userAdapterService.findRoleByUserId(userVO.getId());
                    //创建一个string类型的集合,存储角色id
                    List<String> roleIdList = new ArrayList<>();
                    //遍历角色集合
                    for (Role role : roleList) {
                        //将id存储进集合中
                        roleIdList.add(String.valueOf(role.getId()));
                    }
                    //创建一个跟id集合一样长度的数组
                    String[] ids = new String[roleIdList.size()];
                    roleIdList.toArray(ids);
                    //将角色id设置进用户中
                    userVO.setHasRoleIds(ids);
                } );
            }
            //将集合装进page对象中
            userVoPage.setRecords(userVoList);
            return userVoPage;
        } catch (Exception e) {
            log.error("查询用户列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.PAGE_FAIL);
        }
    }

    @Override
    public UserVo createUser(UserVo userVo)throws ProjectException {
        try {
            //保存用户
            User user = userService.createUser(userVo);
            UserVo userVo1 = BeanConv.toBean(user, UserVo.class);
            if (!EmptyUtil.isNullOrEmpty(userVo1)){
                //绑定附件
                affixFace.bindBusinessId(AffixVo.builder()
                        .businessId(userVo.getId())
                        .id(userVo.getAffixVo().getId())
                        .build());
            }
            //数据回显
            assert userVo1 != null;
            userVo1.setAffixVo(AffixVo.builder()
                    .pathUrl(userVo.getAffixVo().getPathUrl())
                    .businessId(userVo.getId())
                    .id(userVo.getAffixVo().getId())
                    .build());
            //处理角色
            userVo1.setHasRoleIds(userVo.getHasRoleIds());
            return userVo1;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.CREATE_FAIL);
        }
    }

    @Override
    public Boolean updateUser(UserVo userVo) throws ProjectException{
        try {
            //执行修改
            Boolean result = userService.updateUser(userVo);
            if (result){

                List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(userVo.getId());
                //将附件信息的id拿出来
                List<Long> ids = affixVos.stream().map(AffixVo::getId).collect(Collectors.toList());
                //判断集合是否为空
                if (!ids.contains(userVo.getAffixVo().getId())) {
                    //删除图片
                    result=affixFace.deleteAffixVoByBusinessId(userVo.getId());
                    //绑定新图片
                    affixFace.bindBusinessId(AffixVo.builder()
                            .businessId(userVo.getId())
                            .id(userVo.getAffixVo().getId())
                            .build());
                }

            }
            //返回最终结果
            return result;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.UPDATE_FAIL);
        }
    }

    @Override
    public Boolean deleteUser(String[] checkedIds)throws ProjectException {
        try {
            //执行删除
            Boolean result = userService.deleteUser(checkedIds);
            if (result){
                //删除图片
                for (String checkedId : checkedIds) {
                    //删除图片信息
                    affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
                }
            }
            //返回最终结果
            return result;
        } catch (Exception e) {
            log.error("删除用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.DELETE_FAIL);
        }
    }

    @Override
    public UserVo findUserByUserId(Long userId)throws ProjectException {
        try {
            User user = userService.getById(userId);
            return BeanConv.toBean(user,UserVo.class) ;
        } catch (Exception e) {
            log.error("查找用户所有角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_FAIL);
        }
    }

    @Override
    public List<UserVo> findUserVoList()throws ProjectException {
        try {
            List<User> userVoList = userService.findUserVoList();
            return BeanConv.toBeanList(userVoList,UserVo.class);
        } catch (Exception e) {
            log.error("查找用户list异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_LIST_FAIL);
        }
    }
}
